#pragma once

#include <iostream>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "Common.hpp"

class InetAddr
{
public:
    InetAddr() {}

    InetAddr(struct sockaddr_in &addr) : _addr(addr)
    {
        // 网络 -> 主机
        _addr.sin_family = AF_INET;
        _port = ntohs(_addr.sin_port);
        char ipbuff[64];
        inet_ntop(AF_INET, &_addr.sin_addr, ipbuff, sizeof(ipbuff));
        _ip = ipbuff;
    }
    InetAddr(std::string ip, uint16_t port) : _ip(ip), _port(port)
    {
        // 主机 -> 网络
        memset(&_addr,0,sizeof(_addr));
        _addr.sin_port = htons(_port);
        _addr.sin_family = AF_INET;
        inet_pton(AF_INET,ip.c_str(),&_addr.sin_addr);
    }
    InetAddr(uint16_t port):_port(port),_ip()
    {
        // 主机 -> 网络
        memset(&_addr,0,sizeof(_addr));
        _addr.sin_port = htons(_port);
        _addr.sin_family = AF_INET;
        _addr.sin_addr.s_addr = INADDR_ANY;
    }

    std::string Ip(){return _ip;}
    uint16_t port(){return _port;}

    const struct sockaddr_in& NetAddr()
    {
        return _addr;
    }

    // a == b  
    // a.operator==(b) 
    bool operator==(InetAddr& addr)
    {
        return addr._ip == _ip && addr._port == _port;
    }

    std::string StringAdd()
    {
        return _ip + ":" + std::to_string(_port);
    }

    const struct sockaddr *NetAddrPtr()
    {
        return CONV(_addr);
    }
    socklen_t AddrLen()
    {
        return sizeof(_addr);
    }

private:
    std::string _ip;
    uint16_t _port;
    struct sockaddr_in _addr;
};